﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EncryptProject
{
    public partial class SoftKey
    {
        #region 获取芯片 ID

        //***2代支持的函数
        //取得锁的硬件芯片ID:
        //public int GetChipID(ref string OutChipID, string InPath);

        private const byte GET_CHIPID = 0x53;
        public const int USBStatusFail = -50; // USB 操作失败，可能是没有找到相关的指令
        
        /// <summary>
        /// 获取芯片唯一出厂 ID
        /// </summary>
        /// <param name="OutChipID"></param>
        /// <param name="InPath"></param>
        /// <returns></returns>
        public int GetChipID(ref string OutChipID, string InPath)
        {
            int ret; byte[] b_OutChipID = new byte[16];
            int hsignal = CreateSemaphore(0, 1, 1, "ex_sim");
            WaitForSingleObject(hsignal, INFINITE);
            ret = NT_GetChipID(b_OutChipID, InPath);
            ReleaseSemaphore(hsignal, 1, 0);
            CloseHandle(hsignal);
            OutChipID = ByteArrayToHexString(b_OutChipID, 16);
            return ret;

        }

        private string ByteArrayToHexString(byte[] in_data, int nlen)
        {
            string OutString = ""; int n;
            for (n = 0; n < nlen; n++)
            {
                OutString = OutString + in_data[n].ToString("X2");
            }
            return OutString;
        }

        private int NT_GetChipID(byte[] OutChipID, string Path)
        {
            int[] t = new int[8]; int n;
            byte[] array_in = new byte[25];
            byte[] array_out = new byte[25];
            int hUsbDevice = 0;
            if (OpenMydivece(ref hUsbDevice, Path) != 0) return -92;
            array_in[1] = GET_CHIPID;
            if (!SetFeature(hUsbDevice, array_in, 1)) { CloseHandle(hUsbDevice); return -93; }
            if (!GetFeature(hUsbDevice, array_out, 17)) { CloseHandle(hUsbDevice); return -93; }
            CloseHandle(hUsbDevice);
            if (array_out[0] != 0x20) return USBStatusFail;
            for (n = 0; n < 16; n++)
            {
                OutChipID[n] = array_out[1 + n];
            }

            return 0;
        }

        #endregion
    }
}
